package com.sky.controller.user;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/addressBook")
@Api("地址接口")
@Slf4j
public class AdressBookController {
    @Autowired
    private AddressBookService addressBookService;

    /**
     * 新增滴着
     * @param addressBook
     * @return
     */
    @PostMapping
    public Result save(@RequestBody AddressBook addressBook) {
        log.info("添加地址");
        addressBookService.save(addressBook);
        return Result.success();
    }

    /**
     * 条件查询
     * 查询用户所有地址
     */

    @GetMapping("list")
    public Result<List<AddressBook>> list() {
        log.info("查询用户所有地址");
        AddressBook addressBook=new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> list = addressBookService.list(addressBook);
        return Result.success(list);
    }
    /**
     * 条件查询
     * 查询默认地址
     */
    @GetMapping("default")
    public Result<AddressBook> defaultAddress() {
        log.info("查询默认地址");
        AddressBook addressBook=new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(1);
        List<AddressBook>list = addressBookService.list(addressBook);
        if (list!=null){
            return Result.success(list.get(0));
        }
        return Result.error("没有默认地址");
    }
    /**
     * 根据id查询地址
     */
    @GetMapping("{id}")
    public Result<AddressBook> getById(@PathVariable Long id) {
        log.info("根据id查询地址：{}",id);
        AddressBook addressBook = addressBookService.getById(id);
        return Result.success(addressBook);
    }

    /**
     * 根据id修改地址
     */
    @PutMapping
    public Result update(@RequestBody AddressBook addressBook) {
        log.info("修改地址：{}",addressBook);
        addressBookService.update(addressBook);
        return Result.success();
    }

    /**
     * 根据id删除地址
     */
    @DeleteMapping
    public Result delete( Long id) {
        log.info("根据id删除地址：{}",id);
        addressBookService.deleteById(id);

        return Result.success();
    }
    /**
     * 设置默认地址
     */
    @PutMapping("/default")

    public Result setDefaultAddress(@RequestBody AddressBook addressBook){
        log.info("设置默认地址:{}",addressBook);
        addressBookService.setDefaultAddress(addressBook);
        return Result.success();
    }
}
